<template>
  <div class="order_purchase">
    <div class="purchase_head">
      <div class="head_left">
        <div class="round" />
        {{ sbumitBtnText }}
      </div>
      <div class="head_right">
        <el-button class="right_btn" @click="goBack()">返回</el-button>
      </div>
    </div>
    <div class="purchase_content">
      <div class="content_table">
        <div class="content_title">供应商信息</div>
        <div class="info_box mt12">
          <div>
            <div class="info_label">企业名称:</div>
            <div>{{ factoryInfo.anotherName }}</div>
          </div>
          <div>
            <div class="info_label">跟单人员:</div>
            <div>{{ factoryInfo.trackerName }}</div>
          </div>
          <div>
            <div class="info_label">工厂地址:</div>
            <div>{{ factoryInfo.factorAddress }}</div>
          </div>
          <div>
            <div class="info_label">跟单人电话:</div>
            <div>{{ factoryInfo.trackerTel }}</div>
          </div>
          <div>
            <div class="info_label">是否支持开票:</div>
            <div v-if="factoryInfo.isSupportBilling == 1">
              {{ `支持开票(专票${factoryInfo.specialTicket}%)(普票${factoryInfo.ordinaryTicket}%)` }}
            </div>
            <div v-else>不支持开票</div>
          </div>
        </div>
        <div class="content_title mt12">
          商品信息
          <span style="color: #86909c; font-size: 12px">
            待采购(
            <span style="color: #3d3d3d">{{ factoryInfo.list?.length }}</span>
            ) / 已选中(
            <span style="color: #3d3d3d">{{ selectedList?.length }}</span>
            )
          </span>
        </div>
        <el-table
          border
          class="mt12"
          :data="factoryInfo.list"
          style="width: 100%"
          header-cell-class-name="table_head"
          @selection-change="handleSelectionChange"
        >
          <el-table-column v-if="!updateId" label="商品信息" type="selection" width="40" />
          <el-table-column label="商品信息" min-width="330">
            <template #default="{ row }">
              <div class="goods_cell">
                <img class="cell_image" :src="row.mainPicUrl" />
                <div class="cell_product">
                  <div class="product_name">{{ row.productAliasName }}</div>
                  <div class="product_info">{{ row.skuSpecification }}</div>
                  <div class="product_info">SKU编码:{{ row.skuCode }}</div>
                  <div class="product_info">ID：{{ row.productId }}</div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="warrantyTime" label="商品质保日期" max-width="100">
            <template #default="{ row }">
              <span>{{ row.warrantyTime || 0 }}个月</span>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" align="center" min-width="200">
            <template #default="{ row }">
              <RemarkEditor v-model="row.remark" :isEdit="true" />
            </template>
          </el-table-column>
          <el-table-column prop="supplyUnitPrice" label="供应单价" align="center" width="100">
            <template #default="{ row }"> ¥{{ row.supplyUnitPrice }}</template>
          </el-table-column>
          <el-table-column prop="buyNum" label="数量" max-width="100" />
          <el-table-column prop="buyPartNum" label="商品件数" width="100" />
          <template v-if="!isChainTenant">
            <el-table-column prop="measureDataRemark" label="测量数据反馈" width="260" show-overflow-tooltip>
              <template #default="{ row }">
                <div>
                  <div>{{ row.measureDataRemark }}</div>
                  <div style="display: flex; flex-wrap: wrap; max-height: 200px; overflow-y: scroll">
                    <template v-if="row.measureUrl">
                      <el-image
                        v-for="item in row.measureUrl.split(',')"
                        :key="item"
                        style="width: 100px; height: 100px; margin-right: 10px; margin-bottom: 10px"
                        :src="item"
                        :preview-src-list="row.measureUrl.split(',')"
                        preview-teleported
                        fit="cover"
                      />
                    </template>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="discountRate" label="折扣率(%)" width="110">
              <template #default="{ row }">
                <el-input-number
                  class="row_input"
                  :controls="false"
                  :min="0"
                  :precision="2"
                  v-model="row.discountRate"
                  @change="item => changeDisCount(item, row)"
                />
              </template>
            </el-table-column>
            <el-table-column prop="discountAmount" label="折扣(元)" width="105" />
          </template>

          <el-table-column prop="actualAmount" label="采购实付价格" width="120">
            <template #default="{ row }">
              <el-input-number
                class="row_input"
                :disabled="isChainTenant"
                :controls="false"
                :min="0"
                :precision="2"
                v-model="row.actualAmount"
                @change="item => changeActualAmount(item, row)"
              />
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="content_form">
        <div class="form_content">
          <el-form ref="formRef" :model="detailInfo" :rules="rules" label-width="auto" status-icon>
            <el-form-item v-if="!updateId" label="收款账户选择">
              <el-select
                v-model="detailInfo.partnerAccountId"
                filterable
                :filter-method="filterList"
                placeholder="请输入收款账号或户号搜索"
                style="width: 100%"
              >
                <el-option
                  v-for="item in payAccountList"
                  :key="item.partnerAccountId"
                  :label="[item.accountName, item.dictName, item.account].filter(item => item).join('：')"
                  :value="item.partnerAccountId"
                />
              </el-select>
            </el-form-item>
            <el-form-item v-if="isNow === '2'" label="设置定时时间" prop="autoPurchaseTime">
              <div style="display: flex; width: 100%">
                <el-date-picker
                  v-model="detailInfo.autoPurchaseTime"
                  type="datetime"
                  placeholder="请选择"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  format="YYYY-MM-DD HH:mm:ss"
                  style="flex: 1"
                />
                <el-button class="ml10" type="primary" @click="clearTime">清除定时</el-button>
              </div>
            </el-form-item>
            <el-form-item label="预计发货日期" prop="expectedDeliveryDays">
              <!-- <el-date-picker
                v-model="detailInfo.expectedDeliveryTime"
                type="datetime"
                placeholder="请选择"
                value-format="YYYY-MM-DD HH:mm:ss"
                format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%"
              /> -->
              <template #label>
                <div>
                  <p>预计发货日期</p>
                  <p class="f12" style="line-height: 16px">(请填写天数)</p>
                </div>
              </template>
              <el-input-number
                class="input-number"
                v-model="detailInfo.expectedDeliveryDays"
                :min="0"
                :precision="0"
                :controls="false"
                style="width: 100%"
              />
              <!-- <div style="font-size: 12px; color: #86909c">预计发货日期根据付款节点关联，在对应节点配置生效后启动时间计算！</div> -->
            </el-form-item>

            <el-form-item label="发货类型" prop="receivingType">
              <div style="width: 100%">
                <el-radio-group v-model="detailInfo.receivingType" @change="receivingTypeChange">
                  <el-radio :value="1">收货仓库</el-radio>
                  <el-radio :value="2">直发客户</el-radio>
                  <el-radio :value="3">自提货</el-radio>
                </el-radio-group>
              </div>
              <div class="warehouse_content" v-if="detailInfo.receivingType === 1">
                <el-select v-model="detailInfo.receivingWarehouseId" placeholder="请选择仓库" @change="receivingWarehouseId">
                  <el-option
                    v-for="(item, index) in warehouseList"
                    :key="index"
                    :label="item.warehouseName"
                    :value="item.warehouseId"
                  ></el-option>
                </el-select>
              </div>
            </el-form-item>
            <el-form-item label="是否开票" prop="" required>
              <div style="display: flex; justify-content: space-between; width: 100%; background: #f5f7fa; padding: 0 20px">
                <el-radio-group v-model="detailInfo.isBusinessInvoice" @change="isBusinessInvoiceChange">
                  <div class="business-invoice">
                    <div class="is-business-invoice">
                      <el-radio :value="1" :disabled="isChainTenant">开票</el-radio>
                      <el-radio-group
                        class="radio-button"
                        v-model="detailInfo.invoiceType"
                        v-if="detailInfo.isBusinessInvoice === 1"
                        size="small"
                        @change="invoiceTypeChange"
                      >
                        <el-radio-button label="专票" :value="1" />
                        <el-radio-button label="普票" :value="2" />
                      </el-radio-group>
                    </div>
                    <el-radio :value="0" :class="{ 'radio-red': isChainTenant }">不开票</el-radio>
                  </div>
                </el-radio-group>

                <div
                  v-if="factoryInfo.isSupportBilling == 0 && detailInfo.isBusinessInvoice === 1"
                  style="color: #ff3333; font-size: 12px"
                >
                  当前供应商不支持开票，请致电沟通后在提交采购单！
                </div>
              </div>
              <!-- <div class="warehouse_content" v-if="detailInfo.isBusinessInvoice === 1">
                <el-select v-model="detailInfo.invoiceType" placeholder="请选择开票类型" @change="invoiceTypeChange">
                  <el-option label="专票" :value="1" />
                  <el-option label="普票" :value="2" />
                </el-select>
              </div> -->
            </el-form-item>
            <el-form-item
              v-if="!updateId && (factoryInfo.typeCode == 3 || (factoryInfo.typeCode === 0 && !factoryInfo.collectionPlanStatus))"
              label="本次应付金额"
              prop="currentPayableAmount"
            >
              <el-input-number
                class="jzt-input-number"
                :min="0"
                :max="
                  detailInfo?.feeAmount ? detailInfo.commodityPrice + Number(detailInfo?.feeAmount) : detailInfo.commodityPrice
                "
                :precision="2"
                controls-position="right"
                placeholder="请输入"
                v-model.trim="detailInfo.currentPayableAmount"
                style="width: 100%"
              />
            </el-form-item>
            <el-form-item v-if="!updateId" label="本次支付说明">
              <el-input v-model="detailInfo.currentPayableRemark" maxlength="200" placeholder="请输入" />
            </el-form-item>
            <template v-if="!isChainTenant">
              <el-form-item label="其他费用">
                <el-input-number
                  class="jzt-input-number"
                  :min="0"
                  :precision="2"
                  controls-position="right"
                  placeholder="请输入"
                  v-model.trim="detailInfo.otherFee"
                  style="width: 100%"
                  @change="calcTotalPrice"
                />
              </el-form-item>
              <el-form-item label="优惠金额">
                <el-input-number
                  class="jzt-input-number"
                  :min="0"
                  :precision="2"
                  controls-position="right"
                  placeholder="请输入"
                  v-model.trim="detailInfo.discountAmount"
                  style="width: 100%"
                  @change="calcTotalPrice"
                />
              </el-form-item>
            </template>
            <el-form-item label="采购单备注">
              <RemarkEditor v-model="detailInfo.remark" />
            </el-form-item>
            <el-form-item label="附件">
              <image-video-upload
                :file-list="fileList"
                tip="支持doc/docx/pdf/jpg/png，最多上传10个"
                accept=".doc,.docx,.pdf,.jpg,.png"
                multiple
                :max-size="10"
                :max-length="9"
                @upload-success="uploadImage"
                @upload-remove="uploadImageRemove"
              >
                <div class="img_upload">
                  <div style="font-size: 32px">+</div>
                  <div style="color: #86909c">点击上传</div>
                </div>
              </image-video-upload>
            </el-form-item>
          </el-form>
        </div>
        <div class="form_info">
          <div class="info_box" style="display: block">
            <div class="info_title mb10">收货信息</div>
            <div class="info_label mt10">姓名:</div>
            <div>{{ receivingAddress.receivingName }}</div>
            <div class="info_label mt10">电话:</div>
            <div>{{ receivingAddress.receivingMobile }}</div>
            <div class="info_label mt10">
              收货地址:
              <el-button
                v-if="detailInfo.isClose !== 1 && detailInfo.orderStatus !== 3"
                class="ml10"
                type="primary"
                link
                @click="openUpdateReceiptInfoModal"
              >
                修改
                <img class="ml10" style="width: 16px; height: 16px" src="@/assets/images/edit.png" />
              </el-button>
            </div>
            <div>{{ receivingAddress.receivingAreaDetail }}{{ receivingAddress.receivingAddress }}</div>
            <div class="info_title mb10 mt20">买家信息</div>
            <div class="info_label mt10">姓名:</div>
            <div>{{ detailInfo.customerName }}</div>
            <div class="info_label mt10">电话:</div>
            <div>{{ detailInfo.customerMobileCode }}</div>
            <div class="info_label mt10">项目地址:</div>
            <div>{{ detailInfo.customerAddress }}</div>
          </div>
        </div>
      </div>
      <!-- <el-affix position="bottom" :offset="20" style="width: 100%"> -->
      <div class="affix_content">
        <div class="content_left">
          <div class="left_tip">
            <template v-if="!isChainTenant">
              <span class="info_lable">优惠金额：</span>
              <span class="mr20">-¥{{ detailInfo.discountAmount }}</span>
              <span class="info_lable">其他费用：</span>
              <span class="mr20">¥{{ detailInfo.otherFee }}</span>
              <span class="info_lable">折扣金额：</span>
              <span class="mr20">¥{{ detailInfo.discountTotal }}</span>
            </template>
            <template v-if="detailInfo.isBusinessInvoice === 1 && !isChainTenant">
              <span class="info_lable">税额：</span>
              <span class="mr20">¥{{ detailInfo.feeAmount || 0 }}</span>
            </template>
          </div>
          <span item>采购单总价：</span>
          <!-- <span class="mr20">¥{{ detailInfo.totalPrice }}</span> -->
          <span class="mr20">¥{{ detailInfo.commodityPrice ? Number(detailInfo.commodityPrice).toFixed(2) : "0.00" }}</span>
          <span item>应付金额：</span>
          <span class="info_price mr20"
            >¥{{ ((Number(detailInfo.commodityPrice) * 1000 + Number(detailInfo.feeAmount) * 1000) / 1000).toFixed(2) }}</span
          >
          <template
            v-if="!updateId && (factoryInfo.typeCode == 3 || (factoryInfo.typeCode === 0 && !factoryInfo.collectionPlanStatus))"
          >
            <span item>本次应付金额：</span>
            <span class="info_price"
              >¥{{ detailInfo.currentPayableAmount ? Number(detailInfo.currentPayableAmount).toFixed(2) : "0.00" }}</span
            >
          </template>
        </div>
        <div class="content_right">
          <el-button class="btn right_btn" @click="goBack()">取消</el-button>
          <el-button class="btn" type="primary" @click="handelClickCreateProcure(detailInfo)">{{ sbumitBtnText }} </el-button>
        </div>
      </div>
      <!-- </el-affix> -->
    </div>
    <UpdateReceiptInfoDialog
      v-if="updateReceiptInfoFlag"
      title="修改收货信息"
      v-model="updateReceiptInfoFlag"
      :orderDetail="detailInfoCache"
      @success="successHandle"
      :isPostApi="false"
    />

    <dialog-View :isShow="purchaseSuccessFlag" :width="550">
      <div class="procure_success">
        <div><img src="@/static/images/suceess.png" /></div>
        <div>您已成功将当前订单合同发起采购单，采购明细可前往采购单查看 ~</div>
        <div>
          <el-button @click="purchaseSuccessFlag = false">关闭</el-button>
          <el-button type="primary" @click="routeToPurchaseOrder">前往查看</el-button>
        </div>
      </div>
    </dialog-View>

    <dialog-View :isShow="clearTimeFlag" :width="550">
      <div class="time_content">
        <el-icon size="50" color="red">
          <Warning />
        </el-icon>
        <p>您正在执行清除定时采购设置，清除后，此条定时采购计划将被请清除，需要手动进行发起采购，是否继续？</p>
      </div>
      <div class="clear_btn">
        <el-button @click="clearTimeFlag = false">取消</el-button>
        <el-button type="primary" @click="submitClearTime">确定</el-button>
      </div>
    </dialog-View>
  </div>
</template>
<script setup>
import { computed, onMounted, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import {
  createPurchase,
  createTimingPurchase,
  delTimingPurchase,
  getOrderDetail,
  getPayAccountList,
  updateTimingPurchase,
  getShipmentDaysByProducts
} from "@/apis/order";
import RemarkEditor from "@/components/RemarkEditor";
import UpdateReceiptInfoDialog from "../productOrders/components/updateReceiptInfoDialog.vue";
import { ElMessage } from "element-plus";
import { getlistByTenantId } from "@/apis/procure";
import ImageVideoUpload from "@/components/ImageVideoUpload";
import dialogView from "../components/dialogView.vue";

const isChainTenant = JSON.parse(localStorage.getItem("userinfo"))?.isChainTenant; //判断是否是加盟商

const route = useRoute();
const router = useRouter();
const isNow = route.query.isNow;
const orderId = route.query.orderId;
const factorId = route.query.factorId;
const updateId = route.query.updateId;

const formRef = ref();
const detailInfo = ref({});
const detailInfoCache = ref({});
const factoryInfo = ref({});
const warehouseList = ref([]);
const payAccountList = ref([]);
const fileList = ref([]);

const selectedList = ref([]);

const updateReceiptInfoFlag = ref(false);
const purchaseSuccessFlag = ref(false);
const clearTimeFlag = ref(false);

const sbumitBtnText = computed(() => {
  let text = "发起采购订单";
  if (isNow === "2") {
    if (!updateId) text = "设置定时采购订单";
    else text = "修改定时采购订单";
  }
  return text;
});

const goBack = () => router.go(-1);

const routeToPurchaseOrder = () => router.push("/procure/purchase-order");

const calcTotal = ({ buyNum, supplyUnitPrice }, discountRate) => {
  const total = Number(buyNum) * Number(supplyUnitPrice) * (Number(discountRate || 100) / 100);
  return total.toFixed(2);
};

const calcRate = ({ buyNum, supplyUnitPrice }, actualAmount) => {
  const rate = (Number(actualAmount || 0) / Number(buyNum) / Number(supplyUnitPrice)) * 100;
  return rate.toFixed(2);
};

const calcActualTotal = list => {
  return list.reduce((sum, cur) => sum + Number(cur.actualAmount), 0);
};

const calcTotalPrice = () => {
  detailInfo.value.totalPrice = calcActualTotal(selectedList.value); // factoryInfo.value.list

  const actualAmountTotal = calcActualTotal(selectedList.value);

  detailInfo.value.commodityPrice =
    (actualAmountTotal * 1000 + Number(detailInfo.value.otherFee) * 1000 - detailInfo.value.discountAmount * 1000) / 1000;

  detailInfo.value.discountTotal = selectedList.value.reduce(
    (sum, { discountAmount, buyNum }) => sum + discountAmount * buyNum,
    0
  );

  invoiceTypeChange();
};

const getDetailInfo = async () => {
  const { data } = await getOrderDetail(orderId);

  factoryInfo.value = data.orderDetailGroup.find(item => {
    if (item.factorId === factorId) {
      item.list = item.list.map(item => ({
        ...item,
        discountRate: 100,
        discountAmount: 0,
        actualAmount: calcTotal(item, 100)
      }));
      return item;
    }
  });

  detailInfo.value = data;

  if (updateId) {
    const timerProcure = factoryInfo.value.timingPurchaseOrders.find(item => item.updateId === updateId);
    factoryInfo.value.list = timerProcure.productDetailList;
    selectedList.value = timerProcure.productDetailList;
    detailInfo.value = { ...detailInfo, ...timerProcure };
    fileList.value = timerProcure.attachmentFileUrls.split(",").map(item => ({ fileUrl: item }));
  } else {
    detailInfo.value.receivingType = 1;
    detailInfo.value.otherFee = 0;
    detailInfo.value.discountAmount = 0;
    factoryInfo.value.list = factoryInfo.value.list.filter(
      item => item.canPurchase === 1 && item.isSheft === 1 && item.buyNum != 0 && item.buyPartNum != 0
    );
  }

  if (isChainTenant) {
    //是加盟商
    detailInfo.value.isBusinessInvoice = 0;
  } else {
    detailInfo.value.isBusinessInvoice = JSON.parse(JSON.stringify(factoryInfo.value.isSupportBilling));
  }

  calcTotalPrice();
};

const getWarehouseList = async () => {
  const { data } = await getlistByTenantId();
  warehouseList.value = data;
};

const getPayAccountListFn = async () => {
  const { data } = await getPayAccountList({ factoryId: factorId });
  payAccountList.value = data;
};

// 商品选择
const handleSelectionChange = async selected => {
  selectedList.value = selected;
  calcTotalPrice();

  if (selected.length == 0) {
    return;
  }
  let businessSkuIds = [];
  selected?.map(item => {
    businessSkuIds.push(item.businessSkuId);
  });

  const res = await getShipmentDaysByProducts({
    factoryId: factorId,
    businessSkuIds
  });
  if (res.data.rsState == 1) {
    detailInfo.value.expectedDeliveryDays = res.data.maxProduceDays;
    detailInfo.value.originExpectedDays = res.data.maxProduceDays;
  } else {
    ElMessage.error(res.data.rsMsg);
  }
};

// 收货地址信息修改弹窗-回显信息
const openUpdateReceiptInfoModal = () => {
  let ids = [];
  if (receivingAddress.value.receivingAreaIds) {
    ids = receivingAddress.value.receivingAreaIds.split(",");
  }
  detailInfoCache.value = {
    ...receivingAddress.value,
    receivingAreaIds: ids
  };
  updateReceiptInfoFlag.value = true;
};

const changeDisCount = (discountRate, row) => {
  row.actualAmount = calcTotal(row, discountRate);
  const discountTotal = calcTotal(row) - row.actualAmount;
  row.discountAmount = (discountTotal / Number(row.buyNum)).toFixed(2);
  calcTotalPrice();
};

const changeActualAmount = (actualAmount, row) => {
  row.discountRate = calcRate(row, actualAmount);
  const discountTotal = calcTotal(row) - actualAmount;
  row.discountAmount = (discountTotal / Number(row.buyNum)).toFixed(2);
  calcTotalPrice();
};

const filterList = val => {
  return payAccountList.value.filter(item => item.accountName?.includes(val) || item.account?.includes(val));
};

const uploadImage = data => {
  fileList.value.push({
    ...data
  });
};

const uploadImageRemove = index => {
  fileList.value.splice(index, 1);
};

const successHandle = (msg, val) => {
  // 如果组件传过来的省市区汉字没有值，取receivingAddress里的省市区值
  // 弹窗回显省市区，不进行修改，传回来是null
  if (!val.receivingAreaDetail) {
    val.receivingAreaDetail = receivingAddress.value.receivingAreaDetail;
  }
  receivingAddress.value = val;
  // getDetailInfo();
};

const handelClickCreateProcure = async item => {
  if (selectedList.value.length == 0) {
    ElMessage.error("请选择商品");
    return;
  }

  await formRef.value.validate();

  if (detailInfo.value.receivingType == 1 && !detailInfo.value.receivingWarehouseId) {
    ElMessage.error("请选择仓库");
    return;
  }

  if (detailInfo.value.isBusinessInvoice == 1 && !detailInfo.value.invoiceType) {
    ElMessage.error("请选择开票类型");
    return;
  }

  const payAccount = payAccountList.value.find(item => item.partnerAccountId === detailInfo.value.partnerAccountId) || {};

  let params = {
    orderId,
    productInfos: selectedList.value,
    // ...payAccount,
    payAccountId: payAccount.partnerAccountId,
    payAccount: payAccount.account,
    payDictName: payAccount.dictName,
    payAccountName: payAccount.accountName,
    receivingType: item.receivingType,
    receivingWarehouseId: item.receivingWarehouseId,
    receivingName: receivingAddress.value.receivingName,
    receivingMobile: receivingAddress.value.receivingMobile,
    receivingAreaIds: receivingAddress.value.receivingAreaIds,
    receivingAreaDetail: receivingAddress.value.receivingAreaDetail,
    receivingAddress: receivingAddress.value.receivingAddress,
    // expectedDeliveryTime: item.expectedDeliveryTime,
    expectedDeliveryDays: item.expectedDeliveryDays,
    originExpectedDays: item.originExpectedDays,
    otherFee: item.otherFee,
    discountAmount: item.discountAmount,
    currentPayableAmount: String(item.currentPayableAmount || 0),
    currentPayableRemark: item.currentPayableRemark,
    attachmentFileUrls: fileList.value.map(item => item.fileUrl).join(","),
    autoPurchaseTime: item.autoPurchaseTime,
    remark: item.remark,
    isBusinessInvoice: item.isBusinessInvoice,
    invoiceType: item.invoiceType
  };
  if (isNow === "1") {
    await createPurchase(params);
  } else {
    updateId && (params.purchaseOrderId = item.purchaseOrderId);
    !updateId && (await createTimingPurchase(params));
    updateId && (await updateTimingPurchase(params));
  }

  purchaseSuccessFlag.value = true;
};

const clearTime = () => {
  clearTimeFlag.value = true;
};

const submitClearTime = async () => {
  await delTimingPurchase({
    purchaseOrderId: detailInfo.value.purchaseOrderId
  });
  ElMessage({ message: "清楚定时采购单成功", type: "success" });
  goBack();
};

const rules = ref({
  currentPayableAmount: [{ required: true, message: "请输入本次付款金额", trigger: "blur" }],
  expectedDeliveryDays: [{ required: true, message: "请输入预计发货日期", trigger: "blur" }]
});

// 收货地址
const receivingAddress = ref({});

// 发货类型变化
const receivingTypeChange = value => {
  receivingAddress.value = {};
  detailInfo.value.receivingWarehouseId = null;

  if (value == 2 || value == 3) {
    // receivingAddress.value.receivingName = detailInfo.value.customerName;
    // receivingAddress.value.receivingMobile = detailInfo.value.customerMobileCode;
    // receivingAddress.value.receivingAddress = detailInfo.value.customerAddress;
    // receivingAddress.value.receivingAreaDetail= detailInfo.value.customerAreaDetail
    // receivingAddress.value.receivingAreaIds= detailInfo.value.customerAreaIds
    receivingAddress.value.receivingName = detailInfo.value.receivingName;
    receivingAddress.value.receivingMobile = detailInfo.value.receivingMobile;
    receivingAddress.value.receivingAddress = detailInfo.value.receivingAddress;
    receivingAddress.value.receivingAreaDetail = detailInfo.value.receivingAreaDetail;
    receivingAddress.value.receivingAreaIds = detailInfo.value.receivingAreaIds;
  }
};

// 收货仓库变化-收货地址就是选择的仓库地址
const receivingWarehouseId = value => {
  if (value && detailInfo.value.receivingType == 1) {
    receivingAddress.value = warehouseList.value.find(item => {
      if (item.warehouseId == value) {
        item.receivingName = item.manageUserName;
        item.receivingMobile = item.managePhoneNo;
        item.receivingAreaIds = item.provinceId + "," + item.cityId + "," + item.districtId;
        item.receivingAreaDetail = item.provinceName + item.cityName + item.districtName;
        item.receivingAddress = item.address;
        return item;
      }
    });
  } else {
    receivingAddress.value = {};
  }
};

// 是否开票变化
const isBusinessInvoiceChange = () => {
  detailInfo.value.invoiceType = null;
  invoiceTypeChange();
};

// 开票类型变化-算开票金额和税额
const invoiceTypeChange = () => {
  let num = 0;
  // 支持开票-取开票的税率，不支持取0
  if (factoryInfo.value.isSupportBilling == 1) {
    if (detailInfo.value.invoiceType == 1) {
      num = Number(factoryInfo.value.specialTicket || 0);
    } else if (detailInfo.value.invoiceType == 2) {
      num = Number(factoryInfo.value.ordinaryTicket || 0);
    }
  }

  // 小数点2位 *1000 避免长度失真
  detailInfo.value.feeAmount = (((detailInfo.value.commodityPrice * 1000) / 100) * 1000 * num) / 1000000;
  detailInfo.value.feeAmount = Number(detailInfo.value.feeAmount.toFixed(2));
};

onMounted(() => {
  getDetailInfo();
  getWarehouseList();
  getPayAccountListFn();
});
</script>
<style lang="scss">
.order_purchase {
  height: 100%;
  overflow: hidden;

  .radio-red {
    .el-radio__input.is-checked + .el-radio__label {
      color: red;
    }
  }

  .purchase_head {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;
    height: 60px;
    border-bottom: 1px solid #e2e8f0;

    .head_left {
      display: flex;
      align-items: center;
      gap: 10px;
      font-size: 18px;
      color: #131414;
      line-height: 24px;

      .round {
        width: 6px;
        height: 6px;
        background-color: #409eff;
        border-radius: 50%;
      }
    }

    .right_btn {
      background: #f2f3f5;
      border: none;
      width: 90px;
    }
  }

  .purchase_content {
    box-sizing: border-box;
    height: calc(100% - 60px);
    overflow: auto;

    .info_box {
      display: flex;
      gap: 150px;
      padding: 20px;
      background: #f6f8fa;
      line-height: 24px;

      .info_label {
        color: #86909c;
      }

      .info_title {
        color: #86909c;
        font-size: 16px;
      }
    }

    .content_table {
      padding: 20px;

      .content_title {
        display: flex;
        justify-content: space-between;
        font-size: 18px;
        color: #3d3d3d;
        line-height: 22px;
      }

      .table_head {
        background: #f2f6fc !important;
      }

      .goods_cell {
        display: grid;
        grid-template-columns: 80px calc(100% - 100px);
        gap: 20px;

        .cell_image {
          width: 80px;
          height: 80px;
          border-radius: 4px;
        }

        .cell_product {
          .product_name {
            color: #3d3d3d;
            font-weight: 700;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            line-height: 24px;
          }

          .product_info {
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            font-size: 12px;
            color: #86909c;
            line-height: 20px;
          }
        }
      }
    }

    .content_form {
      display: flex;
      border-top: 1px solid #e2e8f0;
      padding-bottom: 52px;

      .form_content {
        box-sizing: border-box;
        width: calc(65% - 1px);
        padding: 20px;
        border-right: 1px solid #e2e8f0;

        .input-number {
          .el-input__inner {
            text-align: left;
          }
        }
      }

      .form_info {
        box-sizing: border-box;
        width: 35%;
        background: #f6f8fa;
      }

      .img_upload {
        box-sizing: border-box;
        padding: 10px;
        width: 80px;
        height: 80px;
        background: #f2f3f5;
        text-align: center;
        color: #c9cdd4;
      }
    }
  }

  .warehouse_content {
    width: 100%;
    height: 58px;
    border: 1px solid #dcdfe6;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    padding-left: 20px;
    overflow: hidden;

    .el-select {
      width: 50%;
    }
  }

  .affix_content {
    position: absolute;
    bottom: 0;
    left: 0;
    width: calc(100% - 40px);
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 20px;
    padding: 10px 20px;
    background: white;
    color: #3d3d3d;
    box-shadow: 0px -3px 10px 0px #04183019;
    z-index: 3;

    .content_left {
      display: flex;
      align-items: end;

      .left_tip {
        font-size: 12px;
      }

      .info_lable {
        color: #86909c;
      }

      .info_price {
        color: #ff3333;
      }
    }
  }

  .procure_success {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;

    div:nth-child(2) {
      margin: 50px;
    }
  }

  .time_content {
    text-align: center;

    p {
      font-size: 14px;
      margin-top: 10px;
    }
  }

  .clear_btn {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 20px 0 0 0;
  }

  .row_input {
    width: 80px !important;

    .el-input__wrapper {
      background: white;
    }
  }

  .plan-nodes {
    .plan-nodes-top {
      font-size: 14px;
      color: rgb(134, 144, 156);

      span {
        margin-right: 20px;
      }
    }

    .plan-nodes-table {
      margin-top: 20px;

      .table_head {
        background: #f2f6fc !important;
      }
    }
  }

  .business-invoice {
    display: flex;
    flex-direction: row;
    align-items: center;

    .is-business-invoice {
      display: flex;
      flex-direction: row;
      align-items: center;
      margin-right: 40px;

      .el-radio {
        margin-right: 10px;
      }

      .radio-button {
        .el-radio-button {
          margin-right: 8px;

          .el-radio-button__inner {
            border-left: 1px solid #dcdfe6;
          }

          &.is-active {
            .el-radio-button__inner {
              border-left: 1px solid #007dff;
            }
          }
        }
      }
    }
  }

  .content_right {
    .btn {
      padding: 8px 32px;
    }

    .right_btn {
      background: #f2f3f5;
      border: none;
      width: 90px;
    }
  }
}
</style>
